<template lang="">
  <div>
    <el-dialog
      v-model="currShow"
      :title="identification ? '新增课程计划' : '编辑课程计划'"
      width="600px"
      :before-close="close"
      :close-on-click-modal="false"
      @open="open()"
    >
      <el-form
        :model="queryForm"
        v-loading="formLoading"
        :rules="rules"
        ref="queryRef"
        label-width="100px"
        class="demo-form-inline"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="cur_enCode">
              <el-select
                v-model="queryForm.cur_enCode"
                class="m-2"
                placeholder="请选择"
                :disabled="identification"
                size="large"
                filterable
                clearable
              >
                <el-option
                  v-for="{ cur_code, cur_name } in curList"
                  :key="cur_code"
                  :label="cur_name"
                  :value="cur_code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上课教师" prop="teacher">
              <el-select
                v-model="queryForm.teacher"
                :disabled="identification"
                class="m-2"
                placeholder="请选择"
                size="large"
                filterable
                clearable
              >
                <el-option
                  v-for="{ tea_code, tea_name } in teaList"
                  :key="tea_code"
                  :label="tea_name"
                  :value="tea_code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始周次" prop="start_weeks">
              <el-select
                v-model="queryForm.start_weeks"
                class="m-2"
                placeholder="请选择"
                :disabled="identification"
                size="large"
                filterable
                clearable
              >
                <el-option v-for="{ code, id } in weeklyList" :key="id" :label="code" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束周次" prop="end_weeks">
              <el-select
                v-model="queryForm.end_weeks"
                class="m-2"
                placeholder="请选择"
                :disabled="identification"
                size="large"
                filterable
                clearable
              >
                <el-option v-for="{ code, id } in weeklyList" :key="id" :label="code" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每周次数" prop="weekNum">
              <el-input
                v-model="queryForm.weekNum"
                @input="validateNumber(queryForm, 'weekNum')"
                :disabled="identification"
                maxlength="2"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="课时" prop="classHour">
              <el-input
                v-model="queryForm.classHour"
                @input="validateNumber(queryForm, 'classHour')"
                :disabled="identification"
                maxlength="2"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="3">
            <p class="class-time">上课时间</p>
          </el-col>
          <el-col :span="21" style="display: flex; justify-content: flex-end;">
            <el-button
              @click="pushClassTime()"
              :disabled="queryForm.classTime.length === 5"
              size="small"
              type="primary"
            >
              + 添加
            </el-button>
          </el-col>
        </el-row>
        <div style="margin-top: 10px">
          <el-form ref="queryTime">
            <el-row style="margin-bottom: 12px">
              <el-col :span="6">
                <h4 class="text-center">星期</h4>
              </el-col>
              <el-col :span="5">
                <h4 class="text-center">开始课次</h4>
              </el-col>
              <el-col :span="5">
                <h4 class="text-center">结束课次</h4>
              </el-col>
              <el-col :span="6">
                <h4 class="text-center">教室</h4>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in queryForm.classTime">
              <el-col :span="6">
                <el-form-item class="r-center" :prop="`classTime[${index}].week`" :rules="rules.week">
                  <el-select v-model="item.week" class="m-2" placeholder="请选择" size="small" filterable clearable>
                    <el-option v-for="{ code, name } in week" :key="code" :label="name" :value="code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  class="r-center"
                  :prop="'classTime.' + index + '.startClassNum'"
                  :rules="rules.startClassNum"
                >
                  <el-select
                    v-model="item.startClassNum"
                    class="w-80 m-2"
                    placeholder="请选择"
                    size="small"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="{ order, end_time, start_time } in dayTimeList"
                      :key="order"
                      :label="`第${order}节`"
                      :value="order"
                    >
                      <span style="float: left">{{ `第${order}节` }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{
                        `${start_time}~${end_time}`
                      }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item class="r-center" :prop="'classTime.' + index + '.endClassNum'" :rules="rules.endClassNum">
                  <el-select
                    v-model="item.endClassNum"
                    class="w-80 m-2"
                    placeholder="请选择"
                    size="small"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="{ order, end_time, start_time } in dayTimeList"
                      :key="order"
                      :label="`第${order}节`"
                      :value="order"
                    >
                      <span style="float: left">{{ `第${order}节` }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{
                        `${start_time}~${end_time}`
                      }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="r-center" :prop="'classTime.' + index + '.classRoom'" :rules="rules.classRoom">
                  <el-select
                    v-model="item.classRoom"
                    class="w-80 m-2"
                    placeholder="请选择"
                    size="small"
                    filterable
                    clearable
                  >
                    <el-option v-for="{ id, class_room } in classRoomList" :key="id" :label="class_room" :value="id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="r-center">
                <el-button
                  v-if="index === 0 || index >= 5 ? false : true"
                  @click="removeClassTime(index)"
                  type="text"
                  size="small"
                >
                  移除
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close(false)">取消</el-button>
          <el-button type="primary" @click="submit(queryRef)" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { insertCoursePlan, editCoursePlan } from '@/api/teaching/course-plan'
import { queryCurList, queryTeaList, queryWeeklyList, queryClassRoomList, queryDayTimeList } from '@/api/public'
import { defineProps, nextTick } from 'vue'
import useCurrentInstance from '@/utils/useCurrentInstance'
import { defineComponent, reactive, ref, watch } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
export default defineComponent({
  props: {
    valueShow: {
      type: Boolean,
      default: false,
    },
    scheduleInfo: {
      type: Object,
      default: () => { },
    },
  },
  setup(props, { emit }) {
    // 变量区域
    const { proxy } = useCurrentInstance()
    const currShow = ref(false)
    const formLoading = ref(false)
    const submitLoading = ref(false)
    const queryRef: any = ref(null)
    const curList: any = ref(null)
    const teaList: any = ref(null)
    const weeklyList: any = ref(null)
    const classRoomList: any = ref(null)
    const dayTimeList: any = ref(null)
    const week = [
      {
        code: 1,
        name: '星期一',
      },
      {
        code: 2,
        name: '星期二',
      },
      {
        code: 3,
        name: '星期三',
      },
      {
        code: 4,
        name: '星期四',
      },
      {
        code: 5,
        name: '星期五',
      },
      {
        code: 6,
        name: '星期六',
      },
      {
        code: 7,
        name: '星期日',
      },
    ]
    const queryForm: any = reactive({
      cur_enCode: null,
      teacher: null,
      start_weeks: null,
      end_weeks: null,
      weekNum: null,
      classTime: [
        {
          week: null,
          startClassNum: null,
          endClassNum: null,
          classRoom: null,
        },
        {
          week: null,
          startClassNum: null,
          endClassNum: null,
          classRoom: null,
        },
      ],
    })
    const rule = { required: true, message: '必填项', trigger: 'blur' }
    const rules = {
      cur_enCode: [rule],
      teacher: [rule],
      start_weeks: [rule],
      end_weeks: [rule],
      weekNum: [rule],
      week: [rule],
      startClassNum: [rule],
      endClassNum: [rule],
      classRoom: [rule],
    }
    const identification = ref(false)

    // 方法区域
    const open = () => {
      if (!props.scheduleInfo) return
      identification.value = true
      nextTick(() => {
        queryForm.cur_enCode = props.scheduleInfo.cur_code
        queryForm.teacher = props.scheduleInfo.tea_code
        queryForm.start_weeks = props.scheduleInfo.start_weeks
        queryForm.end_weeks = props.scheduleInfo.end_weeks
        queryForm.weekNum = props.scheduleInfo.weekNum
        queryForm.classTime = []
        props.scheduleInfo.classTimeList.forEach(element => {
          const obj = {
            week: element.week,
            startClassNum: element.start_class,
            endClassNum: element.end_class,
            classRoom: element.room_code,
          }
          queryForm.classTime.push(obj)
        })
      })
    }

    const close = (val) => {
      emit('closeEditSchedule', val)
      identification.value = false
      nextTick(() => {
        queryRef.value.resetFields()
        queryForm.classTime = new Array(2).fill({
          week: null,
          startClassNum: null,
          endClassNum: null,
          classRoom: null,
        })
      })
    }

    // 获取课程名称下拉列表
    const getCurList = async () => {
      const res: any = await queryCurList()
      curList.value = res.data
    }

    // 获取教师信息列表
    const getTeaList = async () => {
      const res: any = await queryTeaList()
      teaList.value = res.data
    }

    // 获取周次列表信息
    const getWeeklyList = async () => {
      const res: any = await queryWeeklyList()
      weeklyList.value = res.data
    }

    // 获取教室信息列表
    const getClassRoomList = async () => {
      const res: any = await queryClassRoomList()
      classRoomList.value = res.data
    }

    // 获取每天课次时间列表
    const getDayTimeList = async () => {
      const res: any = await queryDayTimeList()
      dayTimeList.value = res.data
    }

    const pushClassTime = () => {
      const obj = {
        week: null,
        startClassNum: null,
        endClassNum: null,
        classRoom: null,
      }
      queryForm.classTime.push(obj)
    }

    const removeClassTime = (index) => {
      queryForm.classTime.splice(index, 1)
    }

    const submit = (formRef) => {
      formRef.validate((valid) => {
        if (!valid) return
        const submitApi = props.scheduleInfo ? editCoursePlan : insertCoursePlan
        formLoading.value = true
        submitLoading.value = true
        submitApi(queryForm)
          .then((res: any) => {
            if (res.data.flag) {
              ElMessage.success(`第${res.data.successList}操作成功`)
            } else {
              ElMessage.error(`第${res.data.failList}操作失败`)
            }
            close(true)
          })
          .finally(() => {
            formLoading.value = false
            submitLoading.value = false
          })
      })
    }

    const validateNumber = (obj, val) => {
      // 用正则表达式检查输入是否合法
      // const regex = /^\d*\.?\d{0,2}$/
      // 如果输入不合法，移除最后一位字符
      // !regex.test(obj[val]) && (obj[val] = obj[val].slice(0, -1))
      obj[val] = obj[val].replace(/[^0-9]/g, '')
    }

    // 钩子函数区域
    watch(
      () => props.valueShow,
      (newVal) => {
        currShow.value = newVal
      }
    )

    // 方法回调区域
    getCurList()
    getTeaList()
    getWeeklyList()
    getClassRoomList()
    getDayTimeList()

    // return返回值
    return {
      currShow,
      formLoading,
      submitLoading,
      queryRef,
      queryForm,
      rules,
      identification,
      curList,
      teaList,
      weeklyList,
      classRoomList,
      dayTimeList,
      week,
      open,
      close,
      submit,
      validateNumber,
      pushClassTime,
      removeClassTime,
    }
  },
})
</script>
<style scoped lang="scss">
.class-time {
  text-align: right;
  font-weight: 700;
  color: #888c92;
}

.text-center {
  text-align: center;
}

.w-80 {
  width: 80%;
}

.r-center ::v-deep .el-form-item__content {
  display: flex;
  justify-content: center;
}

::v-deep .el-dialog {
  display: flex;
  flex-direction: column;

  .el-dialog__body {
    max-height: 80%;
    overflow: auto;
  }
}
</style>
